"use strict";

//app.js
var config = require('./config.js')
var eventBus = require('./utils/eventBus.js')
var myDebugger = require('./utils/myDebugger.js')
var util = require('./utils/util.js')
var api = require('./api/index.js')
var model = require('./model/index.js')

App({
    // ============================================================
    config: config,
    eventBus: eventBus,
    myDebugger: myDebugger,
    util: util,

    // ============================================================
    // 插件
    api: api,
    model: model,

    // ============================================================
    // 全局数据
    globalData: {
        tabPages: {},
        lastTabPageRoute: ''
    },

    // 通过键key获取相应的全局变量
    getGlobalData: function (key) {
        return this.globalData[key] || null;
    },

    // 通过键key值valu保存相应的全局变量
    setGlobalData: function (key, value) {
        this.globalData[key] = value;
    },

    // 获取当前最新tab页面的路由地址
    getLastTabPageRoute: function () {
        return this.globalData.lastTabPageRoute || 'pages/find/index/index'
    },

    // 设置当前最新tab页面的路由地址
    setLastTabPageRoute: function (page) {
        var globalData = this.globalData;
        var route = page.__route__;
        globalData.lastTabPageRoute = route;
    },

    /**
     * 设置tab页面的状态
     * 在onUnload中调用此时state为false
     */
    setTabPageState: function (page, state) {
        var globalData = this.globalData;
        var route = page.__route__;
        globalData.tabPages[route] = state;
    },

    /**
     * 在onShow中调用此时state为true
     */
    checkTabPageStateAndHandle: function (page, callback) {
        var globalData = this.globalData;
        var route = page.__route__;
        var state = globalData.tabPages[route];
        if (state == true) {
            callback && 　callback();
        } else {
            globalData.tabPages[route] = true;
        }
    },

    // 公用方法
    // 从页面栈中获取指定路由地址的页面
    getPageInCurrentPages: function (routeName) {
        var pages = getCurrentPages();
        for (var i in pages) {
            if (pages[i].__route__ === routeName) {
                return page
            }
        }
        return null;
    },
    // ============================================================
    // 生命周期方法

    onLaunch: function () { },

    onShow: function () { },

    onHide: function () { },

    onError: function (msg) {
        console.log('小程序发生bug：', msg);
    }
})